#include "Node.h"
#include "HBSD.h"


using namespace std;

Node::Node(Nodes *nodeManager, string eid) 
{
	activeLink = NULL;
	nodeManager = nodeManager;
	eid = eid;
}

Node::~Node()
{
	activeLink = NULL;
	nodeManager = NULL;
}

bool Node::setLink(Link *link) 
{
	bool set = true;
	if (activeLink == NULL) 
	{
		activeLink = link;
		if (HBSD::log->enabled(Logging::DEBUG)) 
		{
			HBSD::log->debug(string("Associating: ") + link->id + string(" and ") + eid);
		}
	} else 
	{
		if (HBSD::log->enabled(Logging::DEBUG)) 
		{
			HBSD::log->debug(string("Not associating to ") + eid + string(": ") + link->id + string(" already associated to ") + link->remoteEID);
		}

		if (activeLink != link) 
		{
			set = false;
		}
	}

	return set;
}

Link* Node::findLink(Link * excludeLink) 
{
	if (activeLink != NULL) 
	{
		return NULL;
	}

	Link *link = nodeManager->router->routes->getLink(eid, excludeLink);

	if (link == NULL) 
	{
		return NULL;
	}

	if (HBSD::log->enabled(Logging::DEBUG))
	{
		HBSD::log->debug(string("Found link for EID ") + eid + string(": ") + link->id);
	}

	link->conditionalUse(this);
	return link;
}


Link* Node::notifyLink() 
{
	if (activeLink != NULL) 
	{
		// Wake up link.
		activeLink->bundleNotify();
		if (HBSD::log->enabled(Logging::DEBUG))
		{
			HBSD::log->debug(string("Woke up link for EID: ") + this->eid);
		}
		
		return activeLink;
	}
	return findLink(NULL);
}
